package zhou.jan21;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {    //只做数据库操作
	
	BaseDao basedao=new BaseDao();
	Connection con=null;
	PreparedStatement ps=null;
	ResultSet rs=null;
	public User getUserByName(String name) throws SQLException{   //
		
		con=basedao.getCon();
		String sql="select * from user where username=?";
		ps=con.prepareStatement(sql);
		ps.setString(1, name);
		rs=ps.executeQuery();
		String pwd="";
		//int id=0;
		while (rs.next()){    //数据库有名字就会执行这一句，则 pwd不等于""，因此实现不重名。
			pwd=rs.getString("userpwd"); //数据库语句
			//id=r					
		}
		closeData();
		User u=new User(name,pwd);
		return u;
	}
	
	public boolean addUser(User u) throws SQLException{
		boolean flag=false;
		con=basedao.getCon();
		String sql="insert into user (username,userpwd) values(?,?)";
        ps=con.prepareStatement(sql);
		ps.setString(1, u.getName());
		ps.setString(2, u.getPwd());
		
		if(ps.executeUpdate()>0){
				flag=true;
			}		
		closeData();
		
		return flag;
	}
	
	
	public void closeData() throws SQLException{
		if(rs!=null){
			rs.close();
		}
		if(ps!=null){
			ps.close();
		}
		if(con!=null){
			con.close();
		}
	}

}
